//
//  WCNTabBarController.m
//  WCN
//
//  Created by 杨鑫 on 15/5/29.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNTabBarVC.h"
//
//#import "WCNNavigationController.h"
#import "WCNPatientVC.h"
#import "WCNOrdersVC.h"
#import "WCNCaseVC.h"
#import "WCNMeVC.h"
//
#import "Constants.h"
#import "Macros.h"
#import "WCNMyPatientVC.h"
#import "WCDefaultManager.h"
#import "Account.h"
//#import "ChatManager.h"
//#import "EMCDDeviceManager.h"
#import "WCNGenralVC.h"
//#import "WCHuanxinToolByWsj.h"
#import "WCNPatientAndRecordVC.h"
//#import "WCDefaultStanrdForHuanxin.h"
#import "WCBPushToolByWsj.h"
#import "WCNLoginVC.h"
#import "JCAlertView.h"
#import "WCNHomeVC.h"
#import "SQTabbarControllerAnimatedTransitioning.h"
#import "WSJTabarStaticData.h"
//#import <YTXAnimations/UIView+YTXAnimateCSS.h>
//----------
//两次提示的默认间隔
static const CGFloat kDefaultPlaySoundInterval = 3.0;
static NSString *kMessageType = @"MessageType";
static NSString *kConversationChatter = @"ConversationChatter";
static NSString *kGroupName = @"GroupName";
@interface WCNTabBarVC () <UITabBarControllerDelegate>
@property (strong, nonatomic) NSDate *lastPlaySoundDate;


@end

@implementation WCNTabBarVC


- (instancetype)init
{
    self = [super init];
    if (self) {
                  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupUnreadMessageCount) name:BPushBadageChangedNotification object:nil];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //自动登录环信账号
    //[self autoLoginEasebo];
    //    [self configEasebo];
    
    self.delegate = self;
    
    //     WCNPatientAndRecordVC*patientVC =[[WCNPatientAndRecordVC alloc]init];
    WCNHomeVC *homeVC =[WCNHomeVC new];
//    WCNOrdersVC *orderVC = [[WCNOrdersVC alloc] init];
    
    WCNGenralVC *genralVC = [[WCNGenralVC alloc] init];
    //监听 导航栏标题视图
    //    [caseVC.navigationItem addObserver:self
    //                            forKeyPath:@"titleView"
    //                               options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld|NSKeyValueObservingOptionPrior
    //                               context:nil];
    
    WCNMeVC *meVC = [[WCNMeVC alloc] init];
    
    self.viewControllers = @[homeVC, genralVC, meVC];
    
    homeVC.tabBarItem.title = @"首页";
    homeVC.tabBarItem.image = ImageOriginal(@"home");
    homeVC.tabBarItem.selectedImage = ImageOriginal(@"home_s");
    
    //    orderVC.tabBarItem.title = @"订单";
    //    orderVC.tabBarItem.image = ImageOriginal(@"Tab_Order");
    //    orderVC.tabBarItem.selectedImage = ImageOriginal(@"Tab_Order_S");
    
    genralVC.tabBarItem.title = @"圈子";
    genralVC.tabBarItem.image = ImageOriginal(@"friend");
    genralVC.tabBarItem.selectedImage = ImageOriginal(@"圈子");
    
    meVC.tabBarItem.title = @"我的";
    meVC.tabBarItem.image = ImageOriginal(@"me");
    meVC.tabBarItem.selectedImage = ImageOriginal(@"我的");
    
    UITabBar *tarBar = self.tabBar;
    UIView *lineView =[UIView new];
    lineView.frame = CGRectMake(0, 0, kScreenWidth, kOnePX);
    lineView.backgroundColor = HexRGB_WSJ(249, 53, 57);
    
    [self.tabBar addSubview:lineView];
    
    
    
    tarBar.translucent = NO;
    tarBar.barTintColor = [UIColor whiteColor];
    
    for (UITabBarItem *item in tarBar.items) {
        
        [item setTitleTextAttributes:@{NSForegroundColorAttributeName: HexRGB(0x5e606c)} forState:UIControlStateNormal];
        [item setTitleTextAttributes:@{NSForegroundColorAttributeName: HexRGB(0xec1211)} forState:UIControlStateSelected];
        [item setTitlePositionAdjustment:UIOffsetMake(0, -2)];
    }
}

#pragma mark - Setter

- (void)setSelectedIndex:(NSUInteger)selectedIndex
{
    [super setSelectedIndex:selectedIndex];
    _tab_selectedIndex = selectedIndex;
    
    [self tabBarController:self didSelectViewController:self.viewControllers[selectedIndex]];
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
   
}
#pragma mark - UITabBarControllerDelegate
// 当前控制的导航栏项元素
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    self.navigationItem.titleView = viewController.navigationItem.titleView;
    self.navigationItem.leftBarButtonItems = viewController.navigationItem.leftBarButtonItems;
    self.navigationItem.rightBarButtonItems = viewController.navigationItem.rightBarButtonItems;
}
- (void)showBadageOnItem:(NSInteger)index
{
    
    UITabBarItem *item =  self.tabBar.items[index];
    item.badgeValue  =@"new";
    
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (self.selectedIndex == 2) {
        UINavigationItem *navigationItem = object;
        self.navigationItem.titleView = navigationItem.titleView;
    }
}

- (id <UIViewControllerAnimatedTransitioning>)tabBarController:(UITabBarController *)tabBarController animationControllerForTransitionFromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC {
    
    _tab_preIndex = [self.viewControllers indexOfObject:fromVC];
    _tab_selectedIndex =[self.viewControllers indexOfObject:toVC];
    
    return [SQTabbarControllerAnimatedTransitioning new];
}


//- (void)configEasebo
//{
//    [self registerNotifications];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupUntreatedApplyCount) name:@"setupUntreatedApplyCount" object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callOutWithChatter:) name:@"callOutWithChatter" object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callControllerClose:) name:@"callControllerClose" object:nil];
//    [self setupUnreadMessageCount];
//    [self setupUntreatedApplyCount];

//}
//-(void)registerNotifications
//{
//    [self unregisterNotifications];

//    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
//    [[EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
//}
//-(void)unregisterNotifications
//{
//    [[EaseMob sharedInstance].chatManager removeDelegate:self];
//    [[EaseMob sharedInstance].callManager removeDelegate:self];
//}

//- (void)autoLoginEasebo
//{
//    
//    Account *account = [[WCDefaultManager shareMg]account];

    
    //自动登录  获取数据 到数据库  user[@"mobile"]]
    //    [[ChatManager sharedChatManager] autoLoginWithMobile:account.mobile];
    
//}
//- (void)dealloc
//{
    //    [self unregisterNotifications];
    //    NSArray *vcs = self.viewControllers;
    //    UIViewController *vc = vcs[2];
    //    [vc.navigationItem removeObserver:self forKeyPath:@"titleView"];
//}


#pragma mark -收到加入群申请后 自动同意
//- (void)didReceiveApplyToJoinGroup:(NSString *)groupId
//                         groupname:(NSString *)groupname
//                     applyUsername:(NSString *)username
//                            reason:(NSString *)reason
//                             error:(EMError *)error
//{
//     [[EaseMob sharedInstance].chatManager acceptApplyJoinGroup:groupId groupname:groupname applicant:username error:&error];
//    [[EaseMob sharedInstance].chatManager asyncAcceptApplyJoinGroup:groupId groupname:groupname applicant:nil completion:^(EMError *error) {
//        if (!error) {
//            NSString *message =[NSString stringWithFormat:@"%@加入%@群",username,groupname];
//            CoreSVPSuccess(message);
//
//        }
//    } onQueue:nil];
//    NSLog(@"%@",groupId);
//
//
//
//
//}

- (void)setupUnreadMessageCount
{
    
        UIApplication *application = [UIApplication sharedApplication];
        application.applicationIconBadgeNumber =[WCBPushToolByWsj getLatestBadge];
    //      NSInteger totalBadge = [WCHuanxinToolByWsj getaAllUnreadMessageAccout] +[WCBPushToolByWsj getLatestBadge];
    //    application.applicationIconBadgeNumber = totalBadge;
    //     [self reSetTabBarItemWithUnreadCount:[WCHuanxinToolByWsj getGroupUnreadMessageAccout] withItemIndex:2];
    //
    //    [self reSetTabBarItemWithUnreadCount:[WCHuanxinToolByWsj getaChatUnreadMessageAccout] withItemIndex:-1];
}
//- (void)reSetTabBarItemWithUnreadCount:(NSInteger)unreadCount withItemIndex:(NSInteger)index
//{
//    if (index ==-1) {
//        NSDictionary *contDict =@{@"unread_aChat":@(unreadCount)};
//        [[NSNotificationCenter defaultCenter] postNotificationName: achatUnreadNumberNotification object:nil userInfo:contDict];
//        return;
//    }
//    UITabBarItem *item = self.tabBar.items[index];
//    if (unreadCount != 0) {
//        item.badgeValue=@"new";
//    }else{
//       item.badgeValue =nil;
//    }
//
//}

#pragma mark - IChatManagerDelegate 消息变化
//
//- (void)didUpdateConversationList:(NSArray *)conversationList
//{
//    [self setupUnreadMessageCount];
//
//}

// 未读消息数量变化回调
//-(void)didUnreadMessagesCountChanged
//{
//    [self setupUnreadMessageCount];
//}

//- (void)didFinishedReceiveOfflineMessages
//{
//    [self setupUnreadMessageCount];
//}
//- (BOOL)needShowNotification:(NSString *)fromChatter
//{
//    BOOL ret = YES;
//    NSArray *igGroupIds = [[EaseMob sharedInstance].chatManager ignoredGroupIds];
//    for (NSString *str in igGroupIds) {
//        if ([str isEqualToString:fromChatter]) {
//            ret = NO;
//            break;
//        }
//    }
//
//    return ret;
//}

// 收到消息回调
//-(void)didReceiveMessage:(EMMessage *)message
//{
//
//
//    BOOL needShowNotification = (message.messageType != eMessageTypeChat) ? [self needShowNotification:message.conversationChatter] : YES;
//    if (needShowNotification) {
//#if !TARGET_IPHONE_SIMULATOR
//
//        //        BOOL isAppActivity = [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive;
//        //        if (!isAppActivity) {
//        //            [self showNotificationWithMessage:message];
//        //        }else {
//        //            [self playSoundAndVibration];
//        //        }
//        UIApplicationState state = [[UIApplication sharedApplication] applicationState];
//        switch (state) {
//            case UIApplicationStateActive:
//                [self playSoundAndVibration];
//                break;
//            case UIApplicationStateInactive:
//                [self playSoundAndVibration];
//                break;
//            case UIApplicationStateBackground:
//                [self showNotificationWithMessage:message];
//                break;
//            default:
//                break;
//        }
//#endif
//    }
//}
//- (void)playSoundAndVibration{
//    NSTimeInterval timeInterval = [[NSDate date]
//                                   timeIntervalSinceDate:self.lastPlaySoundDate];
//    if (timeInterval < kDefaultPlaySoundInterval) {
//        //如果距离上次响铃和震动时间太短, 则跳过响铃
//        NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
//        return;
//    }
//
//    //保存最后一次响铃时间
//    self.lastPlaySoundDate = [NSDate date];
//
//    // 收到消息时，播放音频
//    [[EMCDDeviceManager sharedInstance] playNewMessageSound];
//    // 收到消息时，震动
//    [[EMCDDeviceManager sharedInstance] playVibration];
//}

//- (void)showNotificationWithMessage:(EMMessage *)message
//{
//    EMPushNotificationOptions *options = [[EaseMob sharedInstance].chatManager pushNotificationOptions];
//    //发送本地推送
//    UILocalNotification *notification = [[UILocalNotification alloc] init];
//
//    notification.fireDate = [NSDate date]; //触发通知的时间
//
//    if (options.displayStyle == ePushNotificationDisplayStyle_messageSummary) {
//        id<IEMMessageBody> messageBody = [message.messageBodies firstObject];
//        NSString *messageStr = nil;
//        switch (messageBody.messageBodyType) {
//            case eMessageBodyType_Text:
//            {
//                messageStr = ((EMTextMessageBody *)messageBody).text;
//            }
//                break;
//            case eMessageBodyType_Image:
//            {
//                messageStr = NSLocalizedString(@"message.image", @"Image");
//            }
//                break;
//            case eMessageBodyType_Location:
//            {
//                messageStr = NSLocalizedString(@"message.location", @"Location");
//            }
//                break;
//            case eMessageBodyType_Voice:
//            {
//                messageStr = NSLocalizedString(@"message.voice", @"Voice");
//            }
//                break;
//            case eMessageBodyType_Video:{
//                messageStr = NSLocalizedString(@"message.video", @"Video");
//            }
//                break;
//            default:
//                break;
//        }
//
//        //        NSString *title = [[UserProfileManager sharedInstance] getNickNameWithUsername:message.from];
//        //        if (message.messageType == eMessageTypeGroupChat) {
//        //            NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
//        //            for (EMGroup *group in groupArray) {
//        //                if ([group.groupId isEqualToString:message.conversationChatter]) {
//        //                    title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, group.groupSubject];
//        //                    break;
//        //                }
//        //            }
//        //        }
//        //        else if (message.messageType == eMessageTypeChatRoom)
//        //        {
//        //            NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
//        //            NSString *key = [NSString stringWithFormat:@"OnceJoinedChatrooms_%@", [[[EaseMob sharedInstance].chatManager loginInfo] objectForKey:@"username" ]];
//        //            NSMutableDictionary *chatrooms = [NSMutableDictionary dictionaryWithDictionary:[ud objectForKey:key]];
//        //            NSString *chatroomName = [chatrooms objectForKey:message.conversationChatter];
//        //            if (chatroomName)
//        //            {
//        //                title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, chatroomName];
//        //            }
//        //        }
//        //
//        //        notification.alertBody = [NSString stringWithFormat:@"%@:%@", title, messageStr];
//    }
//    else{
//        notification.alertBody = NSLocalizedString(@"receiveMessage", @"you have a new message");
//    }
//
#warning 去掉注释会显示[本地]开头, 方便在开发中区分是否为本地推送
//notification.alertBody = [[NSString alloc] initWithFormat:@"[本地]%@", notification.alertBody];

//    notification.alertAction = NSLocalizedString(@"open", @"Open");
//    notification.timeZone = [NSTimeZone defaultTimeZone];
//    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:self.lastPlaySoundDate];
//    if (timeInterval < kDefaultPlaySoundInterval) {
//        NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
//    } else {
//        notification.soundName = UILocalNotificationDefaultSoundName;
//        self.lastPlaySoundDate = [NSDate date];
//    }
//
//    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
//    [userInfo setObject:[NSNumber numberWithInt:message.messageType] forKey:kMessageType];
//    [userInfo setObject:message.conversationChatter forKey:kConversationChatter];
//    notification.userInfo = userInfo;
//
//    //发送通知
//    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
//    UIApplication *application = [UIApplication sharedApplication];
//    application.applicationIconBadgeNumber += 1;
//}


#pragma -mark 被其他设备登陆剔除 后回调
//- (void)didLoginFromOtherDevice
//{
//    [[WCDefaultManager shareMg] logout];
//    //退出环信
//    [[ChatManager sharedChatManager] LogoffHuanxin];
//
//    [JCAlertView showOneButtonWithTitle:@"提示" Message:@"您的账号在别的客户端登陆,请重新登录" ButtonType:JCAlertViewButtonTypeWarn ButtonTitle:@"重新登录" Click:^{
//
//
//        WCNLoginVC *loginVC = [[WCNLoginVC alloc] init];
//        [self.navigationController setViewControllers:@[loginVC] animated:NO];
//
//
//
//    }];
//
//
//}
//

//- (void)switchPageWithIndex:(NSInteger)index
//{
//   [self tabBarController:self didSelectViewController:self.viewControllers[index]];
//
//}
@end
